package com.jimi.controller;


import com.jimi.pojo.Result;
import com.jimi.pojo.User;
import com.jimi.service.UserService;
import com.jimi.utils.JwtUtil;
import com.jimi.utils.PasswordUtils;
import com.jimi.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 注册
     *
     * @param username 用户名
     * @param password 密码
     * @return 返回
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{2,16}") String username,
                           @Pattern(regexp = "^\\S{2,16}") String password) {

        User u = userService.getByUserName(username);
        if (u == null) {
            //注册成功
            userService.register(username, password);
            return Result.success();
        } else {
            //注册失败
            return Result.error("用户名已经存在");
        }

    }


    /**
     * 登录
     * @param username 用户名
     * @param password 密码
     * @return 返回
     */
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{2,16}") String username,
                                @Pattern(regexp = "^\\S{2,16}") String password) {
        User u = userService.getByUserName(username);
        if (u == null) {
            return Result.error("用户名不存在！");
        }

        if (PasswordUtils.matches(password, u.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", u.getId());
            claims.put("username", u.getUsername());
            String token = JwtUtil.genToken(claims);
            log.info("登录成功");
            return Result.success(token);
        } else {
            log.info("登录失败");
            return Result.error("密码错误！");
        }

    }

    /**
     * 获取用户信息
     * @return 返回
     */
    @GetMapping("/userInfo")
    public Result<User> userInfo(){
//        Map<String, Object> map = JwtUtil.parseToken(token);
//        String username = (String) map.get("username");
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    /**
     * 修改用户信息
     * @param user 用户信息
     * @return 状态码
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success();
    }


    /**
     * 修改用户头像
     * @param avatarUrl 头像地址
     * @return 状态码
     */
    @PatchMapping("updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }


    /**
     * 修改用户密码
     * @param params 新密码
     * @return 状态码
     */
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params){
        //参数校验
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if(!StringUtils.hasLength(oldPwd)||!StringUtils.hasLength(newPwd)||!StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要参数!");
        }

        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.getByUserName(username);
        if(!PasswordUtils.matches(oldPwd, loginUser.getPassword())){
            return Result.error("原密码填写不正确!");
        }

        if (!newPwd.equals(rePwd)){
            return Result.error("确认密码不一致!");
        }

        userService.updatePwd(newPwd);
        return Result.success();
    }
}
